import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Checkbox} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions, generateRowSpanData} from './utils';
import {getDetail} from './api';
import {injectIntl, language} from './intl';
import {formatAmount, conventEnumValueToString, formatDateTime, formatPercent} from '../utils';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import PartInvoiceSelectPanel from './PartInvoiceSelectPanel';
import LcCreditSelectPanel from './LcCreditSelectPanel';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import WrappedDatePicker from '../common/WrappedDatePicker';
import WrappedSelect from '../common/WrappedSelect';
import Return from '../common/Return';
import {newOrUpdateValidator} from './validator';
import {transportType, declarePlace, declareType, currency, paymentType} from '../Enum';
import SearchInput from 'Shared/components/SearchInput';
const FormItem = Form.Item;
const declarePlaceList = declarePlace.toList(language);
const declareTypeList = declareType.toList(language);
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {
            shortContainerCount: 0,
            standardContainerCount: 0,
            highContainerCount: 0
        },
        showPartInvoiceSelectPanel: false,
        showLcCreditSelectPanel: false,
        details: [],
        shipmentDetails: []
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: generateRowSpanData(res.data.details, 'packingListCode', ['packingListCode', 'partSaleOrderCode']),
                            shipmentDetails: res.data.shipmentDetails,
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    isLclCheck = e => {
        const isLcl = e.target.checked;
        this.setState({
            data: Object.assign({}, this.state.data, {
                isLcl,
                shortContainerCount: isLcl === true ? 0 : this.state.data.shortContainerCount,
                standardContainerCount: isLcl === true ? 0 : this.state.data.standardContainerCount,
                highContainerCount: isLcl === true ? 0 : this.state.data.highContainerCount
            })
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSelectPartInvoice = records => {
        const retailDetails = [];
        const data = {
            dealerId: records.dealerId,
            brandId: records.brandId,
            dealerCode: records.dealerCode,
            dealerName: records.dealerName,
            country: records.country,
            currency: records.currency,
            invoiceAmount: records.invoiceAmount,
            invoicedDate: records.invoicedDate,
            shipmentType: records.shipmentType,
            origin: records.origin,
            destination: records.destination,
            partContractInvoiceCode: records.code,
            partInvoiceId: records.id,
            isLcl: false,
            paymentType: records.paymentType,
            shortContainerCount: 0,
            standardContainerCount: 0,
            highContainerCount: 0
        };
        records.details.forEach(r => {
            retailDetails.push({
                id: r.id,
                packingListCode: r.packingListCode,
                partSaleOrderCode: r.partSaleOrderCode,
                shipmentDate: r.shipmentDate,
                piCode: r.piCode,
                currency: r.currency,
                partCode: r.partCode,
                partName: r.partName,
                quantity: r.quantity,
                price: r.price,
                totalAmount: r.totalAmount,
                pickingListCode: r.pickingListCode,
                palletCode: r.palletCode
            });
        });
        this.setState({
            details: generateRowSpanData(retailDetails, 'packingListCode', ['packingListCode', 'partSaleOrderCode']),
            data,
            hasOperat: true,
            showPartInvoiceSelectPanel: false,
            shipmentDetails: records.shipmentDetails
        });
    }
    onClosePartInvoiceSelectPanel = () => {
        this.setState({showPartInvoiceSelectPanel: false});
    }
    
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const partId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.partId !== partId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data} = this.state;
        const isValid = newOrUpdateValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickAddBtn = () => {
        this.setState({showPartInvoiceSelectPanel: true});
    }
    onClickLcCredit = () => {
        this.setState({showLcCreditSelectPanel: true});
    }
    onSelectLcCredit = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                lcCreditId: records.id,
                lcCode: records.code
            }),
            hasOperat: true,
            showLcCreditSelectPanel: false
        });
    }
    onCloseLcCreditSelectPanel = () => {
        this.setState({showLcCreditSelectPanel: false});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading, shipmentDetails} = this.state;
        const validateExpectDepartedDate = !data.expectDepartedDate && this.state.validate ? 'error' : null;
        const validateDeclarePlace = !data.declarePlace && this.state.validate ? 'error' : null;
        const validateDeclareType = !data.declareType && this.state.validate ? 'error' : null;
        const validateLcCode = (data.paymentType === paymentType['L/C'] && !data.lcCode) && this.state.validate ? 'error' : null;
        const validateShortContainerCount = data.shortContainerCount === null && this.state.validate ? 'error' : null;
        const validateStandardContainerCount = data.standardContainerCount === null && this.state.validate ? 'error' : null;
        const validateHighContainerCount = data.highContainerCount === null && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions);
        // const newDetails = generateRowSpanData(details, 'packingListCode', ['packingListCode', 'partSaleOrderCode']);
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        }, {
            title: formatMessage({
                id: 'newPanel.column.partSaleOrderCode',
                defaultMessage: '销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        }, {
            title: formatMessage({
                id: 'newPanel.column.pickingListCode',
                defaultMessage: '备料单号'
            }),
            dataIndex: 'pickingListCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.palletCode',
                defaultMessage: '托盘号'
            }),
            dataIndex: 'palletCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.totalAmount',
                defaultMessage: '金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }];

        const shipmentColums = [{
            title: formatMessage({
                id: 'newPanel.column.saleOrderCode',
                defaultMessage: '订单号'
            }),
            dataIndex: 'saleOrderCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.partOrderTypeName',
                defaultMessage: '订单类型'
            }),
            dataIndex: 'partOrderTypeName'
        }, {
            title: formatMessage({
                id: 'newPanel.column.confirmTime',
                defaultMessage: 'PI确认日期'
            }),
            dataIndex: 'confirmTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'newPanel.column.creditAuditedTime',
                defaultMessage: '付款日期'
            }),
            dataIndex: 'creditAuditedTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'newPanel.column.amount',
                defaultMessage: '出运金额'
            }),
            dataIndex: 'amount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.amountMeetRate',
                defaultMessage: '累计金额满足率'
            }),
            dataIndex: 'amountMeetRate',
            render: text => formatPercent(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.isClose',
                defaultMessage: '是否关闭'
            }),
            dataIndex: 'isClose',
            render: text => text ? formatMessage({
                id: 'newPanel.column.isCloseYes',
                defaultMessage: 'Yes'
            }) : formatMessage({
                id: 'newPanel.column.isCloseNo',
                defaultMessage: 'No'
            })
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '发运单信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.dealerName',
                                        defaultMessage: '总代名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.country',
                                        defaultMessage: '国家/地区'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partContractInvoiceCode',
                                        defaultMessage: '发票编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.id ? data.partContractInvoiceCode : <SearchInput
                                            disabled={true}
                                            value={data.partContractInvoiceCode}
                                            id={data.partInvoiceId}
                                            onClickSearchBtn={this.onClickAddBtn} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.invoiceAmount',
                                        defaultMessage: '发票金额'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.invoiceAmount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.invoicedDate',
                                        defaultMessage: '开票日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.invoicedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shipmentType',
                                        defaultMessage: '运输方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(transportType, data.shipmentType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.origin',
                                        defaultMessage: '起运地'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.origin}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.destination',
                                        defaultMessage: '目的地'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.destination}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.expectDepartedDate',
                                            defaultMessage: '预计离港日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateExpectDepartedDate}
                                        required>
                                        <WrappedDatePicker
                                            name="expectDepartedDate"
                                            value={data.expectDepartedDate}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.declarePlace',
                                            defaultMessage: '报关地点'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateDeclarePlace}
                                        required>
                                        <WrappedSelect
                                            allowClear
                                            name="declarePlace"
                                            value={data.declarePlace}
                                            options={declarePlaceList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.declareType',
                                            defaultMessage: '报关类型'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateDeclareType}
                                        required>
                                        <WrappedSelect
                                            allowClear
                                            name="declareType"
                                            value={data.declareType}
                                            options={declareTypeList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.lcCode',
                                        defaultMessage: '信用证编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateLcCode}
                                    required={data.paymentType === paymentType['L/C']}>
                                        {
                                            data.partInvoiceId ? <SearchInput
                                                disabled={true}
                                                value={data.lcCode}
                                                onClickSearchBtn={this.onClickLcCredit} /> : <TextInput
                                                defaultValue={formatMessage({
                                                    id: 'newPanel.operation.selectInvoiceCode',
                                                    defaultMessage: '请先选择发票'
                                                })}
                                                disabled={true}/>
                                        }
                                        
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.isLcl',
                                        defaultMessage: 'LCL'
                                    })} {...FORM_OPTIONS.item}>
                                        <Checkbox
                                            checked={data.isLcl}
                                            name="isLcl"
                                            value={data.isLcl}
                                            onChange={this.isLclCheck}>
                                        </Checkbox>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shortContainerCount',
                                        defaultMessage: '20GP'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateShortContainerCount}
                                    required={data.shipmentType !== transportType.空运 && data.shipmentType !== transportType.快递}>
                                        <LocalizeInputNumber
                                            min={0}
                                            disabled={(data.shipmentType === transportType.空运 || data.shipmentType === transportType.快递) ? true : data.isLcl}
                                            name="shortContainerCount"
                                            value={data.shortContainerCount}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.standardContainerCount',
                                        defaultMessage: '40HQ'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateStandardContainerCount}
                                    required={data.shipmentType !== transportType.空运 && data.shipmentType !== transportType.快递}>
                                        <LocalizeInputNumber
                                            min={0}
                                            disabled={(data.shipmentType === transportType.空运 || data.shipmentType === transportType.快递) ? true : data.isLcl}
                                            name="standardContainerCount"
                                            value={data.standardContainerCount}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.highContainerCount',
                                        defaultMessage: '40GP'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateHighContainerCount}
                                    required={data.shipmentType !== transportType.空运 && data.shipmentType !== transportType.快递}>
                                        <LocalizeInputNumber
                                            min={0}
                                            disabled={(data.shipmentType === transportType.空运 || data.shipmentType === transportType.快递) ? true : data.isLcl}
                                            name="highContainerCount"
                                            value={data.highContainerCount}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.shipmentDetails',
                            defaultMessage: '满足率清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={shipmentColums}
                            rowKey="id"
                            pagination={false}
                            dataSource={shipmentDetails}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '订单清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showPartInvoiceSelectPanel &&
                        <PartInvoiceSelectPanel
                            selectKey={data.id}
                            onCancel={this.onClosePartInvoiceSelectPanel}
                            onSelect={this.onSelectPartInvoice} />
                    }
                    {
                        this.state.showLcCreditSelectPanel &&
                        <LcCreditSelectPanel
                            brandId={data.brandId}
                            dealerCode={data.dealerCode}
                            dealerId={data.dealerId}
                            dealerName={data.dealerName}
                            selectKey={data.id}
                            onCancel={this.onCloseLcCreditSelectPanel}
                            onSelect={this.onSelectLcCredit} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSubmit
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onSubmit(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
